﻿using System;
using System.Windows;
using System.Reflection;
using Ops.Mpc.Models;

namespace Ops.Mpc.States
{
    public class IfTrueStateAction : StateAction
    {
        #region Fields & Properties

        public static readonly DependencyProperty ModelPropertyNameProperty = DependencyProperty.Register("ModelPropertyName", typeof(string), typeof(StateAction), null);
        public string ModelPropertyName
        {
            get
            {
                return (string)this.GetValue(ModelPropertyNameProperty);
            }

            set
            {
                this.SetValue(ModelPropertyNameProperty, value);
            }
        }

        #endregion

        #region Methods

        protected override void OnExecute(object context)
        {
            base.OnExecute(context);
            this.Finish();

        }

        protected override void MoveToNextState()
        {
            Model model = this.GetModel(this.ValidationModelItemName);

            if (model != null)
            {
                PropertyInfo propertyInfo = model.GetType().GetProperty(this.ModelPropertyName);

                if (propertyInfo == null)
                    throw new Exception(string.Format("Property with name '{0}' not found in model '{1}'", this.ModelPropertyName, this.ValidationModelItemName));

                object value = propertyInfo.GetValue(model, new object[] { });

                if (value != null && value.GetType() == typeof(bool))
                {
                    if (((bool)value))
                        base.MoveToNextState();
                }
                else
                {
                    throw new Exception(string.Format("Property with name '{0}' found in model '{1}' must be boolean value type", this.ModelPropertyName, this.ValidationModelItemName));
                }
            }
            else
                throw new Exception(string.Format("Model with name '{0}' was not found for {1}", this.ValidationModelItemName, this.GetType().Name));

           
        }
        #endregion
    }
}
